package com.pan.utils;

import com.pan.crawler.entity.HouseInfo;
import com.pan.old.pa.entity.Info;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class WriteFileCSV {

    private File file;

    private FileWriter fileWriter;

    public WriteFileCSV(String fileName){
        this(fileName,true);
    }

    public WriteFileCSV(String fileName,boolean append){
        String path = System.getProperty("user.dir");
        String dataDirPath = path+"\\data";
        String filePath = dataDirPath+"\\"+fileName+".csv";
        File dirFile = new File(dataDirPath);
        if (!dirFile.exists()){
            dirFile.mkdir();
        }
        File file = new File(filePath);
        if (!file.exists()){
//            throw new RuntimeException("文件名重复");
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        this.file = file;
        try {
            this.fileWriter = new FileWriter(file,append);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public void startWriteData(List<HouseInfo> infoList){
        String content = infoList.get(1).getTitleLine()
                + infoList.stream().map(HouseInfo::getCsvLine).reduce((x,y)->x+y).get();
        try {
            fileWriter.append(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void append(String str){
        try {
            fileWriter.append(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void appendData(List<HouseInfo> infoList){
        String content = infoList.stream()
                .map(HouseInfo::getCsvLine)
                .reduce((x,y)->x+y).get();
        try {
            fileWriter.append(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void close(){
        try {
            this.fileWriter.flush();
            this.fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
